<?php
class Frontend_Service_Authentication
{
    /**
     * @var Zend_Auth
     */
    protected $_auth;

    /**
     * @var Zend_Auth_Adapter_DbTable
     */
    protected $_authAdapter;

    /**
     * Authenticate a user
     *
     * @param  array $info
     * @return boolean
     */
    public function authenticate($info)
    {
        $adapter = $this->getAuthAdapter($info);
        $auth    = $this->getAuth();
        $result  = $auth->authenticate($adapter);

        if (!$result->isValid()) {
            return false;
        }

        $user = Wenda::getModel('User')->findByName($info['name']);
        $auth->getStorage()->write($user->toArray());

        return true;
    }

    /**
     * Get auth object
     * 
     * @return Zend_Auth
     */
    public function getAuth()
    {
        if (null === $this->_auth) {
            $this->_auth = Zend_Auth::getInstance();
        }
        return $this->_auth;
    }

    /**
     * Clear auth object
     */

    public function clear()
    {
        $this->getAuth()->clearIdentity();
    }

    /**
     * Set the auth adpater.
     *
     * @param Zend_Auth_Adapter_Interface $adapter
     */
    public function setAuthAdapter(Zend_Auth_Adapter_Interface $adapter)
    {
        $this->_authAdapter = $adapter;
    }

    /**
     * Get auth adpater
     * 
     * @param array $user
     * @return Zend_Auth_Adapter
     */
    public function getAuthAdapter($user)
    {
        if (null === $this->_authAdapter){
            $authAdapter = new Zend_Auth_Adapter_DbTable(
                Zend_Db_Table_Abstract::getDefaultAdapter(),
                'user',
                'name',
                'password'
            );
            $this->setAuthAdapter($authAdapter);
            $this->_authAdapter->setIdentity($user['name']);
            $this->_authAdapter->setCredential(md5($user['password']));
        }
        return $this->_authAdapter;
    }
}
